<template>
	<view class="login-page  " :class="themeName">
		<!-- #ifndef  H5 -->
		<!-- <custom-navbar is-back title="登录" ></custom-navbar> -->
		<!-- #endif -->
		
		
		<view class="login-content">
			<!-- <image class="imagei" src="/static/img/Home/logo.png"></image> -->
            <image class="imagei" :src="appLogoPath" :style="appLogoStyle" mode="heightFix"></image>
			<view class="welcome">欢迎回来！</view>
			<view class="login-mode">
				<view :class="['login-mode-item', {'active' : loginModeValue === loginWays.ACCOUNT }]" @click="changeLoginMode(loginWays.ACCOUNT)">账号密码</view>
				<view :class="['login-mode-item', {'active' : loginModeValue === loginWays.SMS_CODE }]" @click="changeLoginMode(loginWays.SMS_CODE)">手机登录</view>
			</view>
			
			<view class="form-wrap">
				<template v-if="loginModeValue === loginWays.ACCOUNT">
					<AccountAndSmsLogin key="1" :login-type="loginWays.ACCOUNT" :is-agree="isAgree" @success="loginFun" @agree="openAgreeModel"></AccountAndSmsLogin>
				</template>
				<template v-if="loginModeValue === loginWays.SMS_CODE">
					<AccountAndSmsLogin key="2" :login-type="loginWays.SMS_CODE" :is-agree="isAgree" @success="loginFun" @agree="openAgreeModel"></AccountAndSmsLogin>
				</template>
			</view>
			
			<view class="m-t-40" >
			    <u-checkbox v-model="isAgree" :active-color="themeColor" shape="circle" :label-disabled="true">
			        <view class="sm flex">
			            已阅读并同意
			            <router-link data-theme="" to="/pagesUser/pages/server_explan/server_explan?type=1">
			            	<view class="agreement">《服务协议》</view>
			            </router-link>
			            和
			            <router-link to="/pagesUser/pages/server_explan/server_explan?type=2">
			            	<view class="agreement">《隐私协议》</view>
			            </router-link>
			        </view>
			    </u-checkbox>
			</view>
			<view class="m-t-40 flex row-between " >
				<view class="" >
					<router-link to="/pages/forget_pwd/forget_pwd">
						<text style="font-size: 27rpx;color: #fff;">
							忘记密码?
						</text>
						
					</router-link>
				</view>
				<view >
					<router-link to="/pages/register/register">
						
						<text style="font-size: 27rpx; color: #fff;">注册</text>
					</router-link>
				</view>
				
			</view>
		</view>
		
		
		<user-agreement-modal 
			:is-agree.sync="isAgree" 
			:visible.sync="showModel" 
			:agreemen-name="AgreemenName" 
			:agreemen-user-name="AgreemenUserName">
		</user-agreement-modal>
	
		
		
		
		
		<!-- #ifdef MP-WEIXIN -->
		<mplogin-popup v-model="showLoginPop" :logo="appConfig.logo" :title="appConfig.shop_name"
			:login-data="loginData" @close="closePopup" @update="handleSubmitInfo" />
		<!--  #endif -->
	</view>
</template>

<script>
	
	import {
		mapMutations,
		mapActions,
		mapGetters
	} from "vuex";
	import AccountAndSmsLogin from "./components/AccountAndSmsLogin.vue";
	import SmsCodeLoginVue from "./components/SmsCodeLogin.vue";
	import {
		apiAuthLogin,
		apiAccountLogin,
		apiLoginCaptcha,
		apiToutiaoAuthLogin,
		apiAppWxLogin,
		apiUpdateUser,
		apiCheckMobile,
	} from "@/api/app";
	import wechath5 from "@/utils/wechath5";
	import {
		isWeixinClient,
		currentPage,
		client,
		trottle
	} from "@/utils/tools";
	import Cache from "@/utils/cache";
	import {
		BACK_URL,
		INVITE_CODE
	} from "@/config/cachekey";
	import {
		getCode,
		getUserProfile
	} from "@/utils/login";
	import {
		apiPolicyAgreement
	} from "@/api/app";
	import {tabBarList} from "@/const.js"
    import staticLogoImg  from "@/static/img/Home/logo.png"
    import { baseURL, basePath } from '@/config/app'
	const loginType = {
		ACCOUNT: 1,
		SMS_CODE: 2,
		OTHER: 3,
	};
	const LOGIN_WAYS = {
		ACCOUNT: 1,
		SMS_CODE: 2,
		OTHER: 3,
	}
	export default {
		components: {
			AccountAndSmsLogin,
			SmsCodeLoginVue
		},
		data() {
			// 登录方式： 1 账号密码登录  2 手机号登录， 3 (其他)一键登录
			
			return {
				// 登录方式： 1 账号密码登录  2 手机号登录， 3 (其他)一键登录
				loginWays: {
					...LOGIN_WAYS
				},
				// 登录方式： 1 账号密码登录  2 手机号登录， 3 一键登录
				loginModeValue: LOGIN_WAYS.ACCOUNT,
				
				isWeixin: "",
				showLoginPop: false,
				loginData: {},
				isAgree: false,
				showModel: false,
				AgreemenName: "",
				AgreemenUserName: "",
                isRead: false
			};
		},
		computed: {
		    // 项目 logo, 正常来说，这个链接是当前域名下的链接，
			appLogoPath () {
                // 如果存在就返回预期的logo图片，
		        if (this.appConfig.logo && this.appConfig.logo.includes(baseURL)) {
		            return this.appConfig.logo
		        }
                // 这里的意思 是准备好了，再去加载本地的静态logo图片, 主要是因为其中一个app已经上过版本了，另外一个项目，没上线。会存在一些问题。
                // isRead 做了一个延时设置,500毫秒设为true, 
                if (this.isRead) {
                    return staticLogoImg
                }
                return ''
			},
            appLogoStyle () {
                // 	width: 223rpx !important;
			// height: 81rpx !important;
			// position: absolute;
			// left: 98rpx;
			// margin-top: 230rpx;
                const { mobile_logo_w, mobile_logo_h, mobile_logo_l, mobile_logo_t } = this.appConfig
                const obj = {
                    width: mobile_logo_w ? `${mobile_logo_w}rpx` : '223rpx',
                    height: mobile_logo_h ? `${mobile_logo_h}rpx` : '81rpx',
                    left: mobile_logo_l ? `${mobile_logo_l}rpx` : '98rpx',
                    top: mobile_logo_t ? `${mobile_logo_t}rpx` : '230rpx'
                }
                return {
                    ...obj
                }
            },
			// 开启手机号注册
			isPhoneRegister() {
				const {
					register_way
				} = this.appConfig;
				if (!register_way) {
					return false;
				}
				return register_way.some((item) => item == 1);
			},
			// 开启强制绑定手机号
			isBindMobile() {
				const {
					coerce_mobile
				} = this.appConfig;
				return coerce_mobile;
			},
			
			
			// 开启小程序微信授权
			isMnpWxAuth() {
				const {
					mnp_wechat_auth
				} = this.appConfig;
				return mnp_wechat_auth;
			},
		
			// 开启小程序微信授权
			isOaWxAuth() {
				const {
					h5_wechat_auth
				} = this.appConfig;
				return h5_wechat_auth;
			},
			// 开启app微信授权
			isAPPWxAuth() {
				const {
					app_wechat_auth
				} = this.appConfig;
				return app_wechat_auth;
			},
			// 开启公众号微信自动登录
			isOaWxAutoLogin() {
				const {
					h5_auto_wechat_auth
				} = this.appConfig;
				return h5_auto_wechat_auth;
			},
			// 开启小程序头条登录
			isToutiaoAuth() {
				const {
					toutiao_auth
				} = this.appConfig;
				return toutiao_auth;
			},
		
		},
		onLoad() {
			this.getPolicyAgreement();
			this.mnpLogin = trottle(this.mnpLogin);
			this.appLogin = trottle(this.appLogin);
			this.getCodeUrl = trottle(this.getCodeUrl);
			this.ttLogin = trottle(this.ttLogin);
			// #ifdef H5
			this.oaAutoLogin();
			// #endif
		},
		onUnload() {},
        mounted() {
            const vm = this
            setTimeout(() => {
                vm.isRead = true
            }, 500)
        },
		methods: {
			...mapMutations(["login"]),
			...mapActions(["getUser"]),
			/**
			 * @param {number} mode 登录方式的修改 1 账号密码登录  2 手机号登录， 3 一键登录
			 */
			changeLoginMode(mode = LOGIN_WAYS.ACCOUNT) {
				this.loginModeValue = mode
			},
			// 获取服务协议
			getPolicyAgreement() {
				apiPolicyAgreement({
					type: 1,
				}).then((res) => {
					this.AgreemenName = res.name;
				});
				apiPolicyAgreement({
					type: 2,
				}).then((res) => {
					this.AgreemenUserName = res.name;
				});
			},
			// 小程序微信登录
			async mnpLogin() {
				if (!this.isAgree) {
					this.openAgreeModel()

					return;
				}
				const {
					userInfo: {
						avatarUrl,
						nickName,
						gender
					},
				} = await getUserProfile();
				uni.showLoading({
					title: "登录中...",
					mask: true,
				});
				const wxCode = await getCode();
				const data = await apiAuthLogin({
					code: wxCode,
					nickname: nickName,
					headimgurl: avatarUrl,
				});
				if (data.is_new_user) {
					uni.hideLoading();
					this.showLoginPop = true;
					this.loginData = data;
				} else {
					this.loginHandle(data);
				}
				// this.loginHandle(data)
			},
			getCodeUrl() {
				if (!this.isAgree) {
					// this.$toast({ title: "请阅读并同意《服务协议》《隐私协议》" });
					this.openAgreeModel()

					return;
				}
				wechath5.getWxUrl();
			},
			// 公众号微信登录
			async oaLogin(code) {
				if (!code) return;
				const data = await wechath5.authLogin(code);
				this.loginHandle(data);
			},
			oaAutoLogin() {
				// H5微信登录
				const {
					code
				} = this.$Route.query;
				this.isWeixin = isWeixinClient();
				// if (this.isLogin) {
				// 	// 已经登录 => 首页
				// 	uni.switchTab({
				// 		url: "/pages/index/index",
				// 	});
				// 	return;
				// }
				if (code) {
					// 带有code => 登录
					return this.oaLogin(code);
				}
				if (this.isWeixin && this.isOaWxAutoLogin) {
					// 开启自动授权登录
					this.getCodeUrl();
				}
			},
			// app微信登录
			async appLogin() {
				if (!this.isAgree) {
					// this.$toast({ title: "请阅读并同意《服务协议》《隐私协议》" });
					this.openAgreeModel()

					return;
				}
				uni.login({
					provider: "weixin",
					success: (res) => {
						uni.showLoading({
							title: "登录中...",
							mask: true,
						});
						const {
							openid,
							access_token
						} = res.authResult;
						apiAppWxLogin({
								openid,
								access_token,
							})
							.then((res) => {
								this.loginHandle(res);
							})
							.finally((res) => {
								uni.hideLoading();
							});
					},
				});
			},
			// 账号登录
			async loginFun(config) {
				uni.showLoading({
					title: "登录中...",
					mask: true,
				});
				apiAccountLogin({
					scene: this.loginModeValue,
					...config
				}).then((res) => {
					this.loginHandle(res);
				}).finally(() => {
					uni.hideLoading();
				})
			},
			// 登录结果处理
			async loginHandle(data) {
				this.login(data);
				this.getUser();
				// 更新购物车
				this.$store.dispatch("getCartNum");
				uni.hideLoading();
				if (this.isBindMobile && !data.mobile) {
					return this.$Router.replace("/pages/bind_mobile/bind_mobile");
				}
				this.goBack();
			},
			goBack() {
				const vm = this
				const pages = getCurrentPages()
				const cacheUrl = Cache.get(BACK_URL)
				
				pages.forEach(item => {
					console.log('pages', item.route, item)
				})
				// return
				if (pages.length > 1) {
					uni.reLaunch({
						url: '/pages/index/index'
					})
					return
					// @todo 这里存在逻辑错乱，返回上一个页面时，应该去掉注册页面。这里先临时性的让他回到首页.
					// 在跳转到注册页面时，应该使用 redirectTo，或者进
					const prePage = pages[pages.length - 2]
					if (prePage.route.includes('pages/login/login') || prePage.route.includes('pages/register/register')) {
						uni.reLaunch({
							url: '/pages/index/index'
						})
						return
					} 
					uni.navigateBack({
						delta: 1,
						fail: () => {
							vm.$Router.replaceAll("/pages/index/index");
						}
					});
					
					
				} else if (cacheUrl) {
					console.log("登录时进到goBack函数， 1", Cache.get(BACK_URL))
					if (cacheUrl === '/') {
						uni.reLaunch({
							url: '/pages/index/index'
						})
					}  else if (tabBarList.includes(cacheUrl)){
						uni.reLaunch({
							url: cacheUrl
						})
					} else {
						uni.navigateTo({
							url: cacheUrl
						})
					}
				} else {
					uni.reLaunch({
						url: '/pages/index/index'
					})
				}
				Cache.remove(BACK_URL);
			},
			
			

			
			// 头条小程序登录
			async ttLogin() {
				const code = await getCode();
				const [err, res] = await uni.getUserInfo();
				if (!res) {
					this.openSetting();
					return;
				}
				const {
					avatarUrl,
					nickName
				} = res.userInfo;
				uni.showLoading({
					title: "登录中...",
				});

				apiToutiaoAuthLogin({
						code,
						avatarUrl,
						nickName,
					})
					.then((res) => {
						this.loginHandle(res);
					})
					.catch((res) => {
						uni.hideLoading();
					});
			},
			openSetting() {
				uni.showModal({
					title: "温馨提示",
					content: "您已拒绝授权，是否前往设置打开个人信息授权？",
					confirmColor: this.themeColor,
					success(res) {
						if (res.confirm) {
							uni.openSetting();
						}
					},
				});
			},
			async handleSubmitInfo(e) {
				const loginData = this.loginData;
				const res = await apiUpdateUser(e, loginData.token);
				this.loginHandle(loginData);
			},
			closePopup() {
				this.showLoginPop = false;
			},
			openAgreeModel() {
				this.showModel = true;
			}
		}
		
	};
</script>
<style lang="scss" scoped>
	uni-page-body {
		height: 100vh;
	}
	.login-page {
		height: 100%;
		background-image: linear-gradient(to bottom, #ff8200 0%, #F7F7F7 60%);
	}	
	.login-content {
		background-image: url('@/static/img/Home/bj.jpg');
		background-size: 100% 100%;
		background-repeat: no-repeat;
		width: 100%;
		display: flex;
		flex-direction: column;
		height: 100%;
		padding: 0 58rpx ;
		position: relative;
		.imagei {
			position: absolute;
		}
		.welcome {
			margin-top: 350rpx;
			font-size: 63rpx;
			padding: 30rpx;
			color: #fff;
		}
		.login-mode {
			
			display: flex;
			flex-direction: row;
			justify-content: flex-start;
			margin-top: 90rpx;
			
		}
		.login-mode-item {
			width: 190rpx;
			font-size: 32rpx;
			color: #fff;
			text-align: center;
			transition: all 200ms;
			&.active {
				font-weight: 700;
			}
		}
		.form-wrap {
			margin-top: 40rpx;
		}
		.agreement {
		    @include font_color;
		}
	}
</style>